package labilabyrinth.game;

import labilabyrinth.enums.GameState;
import android.graphics.Canvas;
import android.view.SurfaceHolder;

public class GameLoop extends Thread {
	
	private SurfaceHolder surfaceHolder;
	private final float nanoToSec = 1.0f / 1000000000.0f;
	private GameSurface gameSurface;
	private Ball ball;
	private boolean isRunning = false;
	private float lastTime = 0;
    private long sleepTime = 0;

	public GameLoop(SurfaceHolder surfaceHolder, GameSurface gameSurface,Ball b) {
		this.surfaceHolder = surfaceHolder;
		this.gameSurface = gameSurface;
		this.ball = b;
		lastTime = System.nanoTime();
	}
	

	public void setRunning(boolean run) {
		this.isRunning = run;
		lastTime = System.nanoTime();
	}
	
	
	@Override
    public void run() {
         Canvas c;
         while (isRunning) {
             c = null;
             try {
                 c = surfaceHolder.lockCanvas(null);
                 synchronized (surfaceHolder) {
                	 float current = System.nanoTime();
                	 float dT = current - lastTime;
                	 dT *= nanoToSec;
                	 if(gameSurface.state.equals(GameState.RUNNING))
                		 ball.updatePhysics(gameSurface.getAxisX(), gameSurface.getAxisY(), dT);
                     gameSurface.onDraw(c,dT);
                     lastTime = current;
                 }
             } finally {
                 if (c != null) {
                	 surfaceHolder.unlockCanvasAndPost(c);
                 }
             }
             try {
            	 if(sleepTime>0){
            		 sleep(sleepTime);
                 }
             	} catch (InterruptedException ex) {}
         }
    }
 }
